package cn.com.haopy.yue.ai.core.config.shiro;

import cn.com.haopy.yue.ai.core.utils.ConstantHeader;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.util.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;

public class WebSessionManager extends DefaultWebSessionManager {
    public static final String LOGIN_TOKEN_KEY_ADMIN = ConstantHeader.LOGIN_TOKEN_KEY_ADMIN;
    private static final String REFERENCED_SESSION_ID_SOURCE = "Stateless request";


    public WebSessionManager() {
        super();
        setGlobalSessionTimeout(MILLIS_PER_HOUR * 10); // 10小时
//        setGlobalSessionTimeout(MILLIS_PER_MINUTE * 30); // 30分钟（等保测评要求）
        setSessionIdCookieEnabled(true);
        setSessionIdUrlRewritingEnabled(false);
    }

    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
        String id_admin = WebUtils.toHttp(request).getHeader(LOGIN_TOKEN_KEY_ADMIN);
        if (!StringUtils.isEmpty(id_admin)) {
            System.out.println("getSessionId admin:" + id_admin);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, REFERENCED_SESSION_ID_SOURCE);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, id_admin);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
            return id_admin;
        }

        return super.getSessionId(request, response);

    }
}
